const fs = require('fs');
const stat = fs.stat;
const path = require('path');
const echoTs = (_path,routes)=>{
  var mainData = fs.readFileSync(path.resolve(_path,'../../main.ts'),'utf-8');
  let echo = `
  ${routes}
  //添加模拟路由
  app.use((app)=>{
    let routeObj = {};
    routes.forEach(item=>{
      const rootMeta = item.meta || {};
      if(item.children && item.children.length > 0){
        item.children.forEach(r=>{
          routeObj[r.name] = {name:r.name,path:r.path,meta:{...rootMeta,...r.meta}};
        })
      }else{
        routeObj[item.name] = {name:item.name,path:item.path,meta:item.meta};
      }
    })
    let nowRoute = routeObj['${_path.split('\\').pop()}']; 
    //判断是否登录
    const token = $local(appToken);
    const baseStore = $local(baseStoreState);
    document.title = '';
    //在离线状态下且此时的路由配置不允许
    if(!baseStore.netState && nowRoute?.meta && (nowRoute.meta.permissions as Array<any> || []).indexOf('offLine') == -1){
      $pathTo('@'+'${process.env.VUE_APP_HOME}')
      return;
    }
    //不登录，且此页面需要登录。跳转到登录页面
    if(!token && nowRoute?.meta && nowRoute.meta.public !== true){
      $pathTo('${process.env.VUE_APP_LOGIN}')
      return;
    }
    //已经登录，此时页面为登录页面。跳转到首页
    if(token && nowRoute?.meta && nowRoute.meta.isLogin){
      $pathTo('@'+'${process.env.VUE_APP_HOME}')
      return;
    }
    //赋值全局变量
    app.config.globalProperties.$route = nowRoute;
  })`
  mainData = mainData.replace('App.vue','temporaryEntry.vue')
  return mainData.replace('setupRouter(app)',echo)
}
const echoVue = ()=>{
  return(`<template>
  <!-- 导航栏 -->
  <van-sticky class="app-header" ref="navbarRef" v-if="meta.navbar" >
    <van-nav-bar
      :title="meta.title" 
      :border="false">
      <template #left>
        <van-icon v-if="meta.navbar?.left !== false" @click="handleLeft" name="arrow-left" size="18" />
      </template>
      <template #right>
        <t-navBarRight v-if="meta.navbar?.right !== false" @checked="handleClick" :permissions="meta.permissions" :keyDict="meta.keyDict" />
      </template>
    </van-nav-bar>
  </van-sticky>
  <!-- 组件body -->
  <div 
    :style="containerStyle"
    :class="{
      'app-container': meta.navbar && meta.tabbar,
      'app-container-none': !meta.navbar && !meta.tabbar,
      'app-container-navbar': meta.navbar && !meta.tabbar,
      'app-container-tabbar': !meta.navbar && meta.tabbar,
    }">
    <t-index ref="routerComponent"></t-index>
  </div>
  <!-- 底部tabbar -->
  <van-tabbar
    v-if="meta.tabbar" 
    v-model="active"
    class="app-van-tabbar--self" 
    active-color="white" 
    ref="tabbarRef">
    <template v-for="(item,index) in main" :key="index">
      <van-tabbar-item @click="$pathTo(item.path)" :to="item.to" :icon="item.icon" >{{ item.title }}</van-tabbar-item>
    </template>
  </van-tabbar>
  <!-- float框 -->
  <t-float @checked="floatClick" :permissions="meta.permissions" :keyDict="meta.keyDict"></t-float>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, Ref,reactive,watch, computed,toRefs, nextTick} from 'vue'
import { useStore } from "vuex"
import {$pathTo} from '@/utils'
import tIndex from "./index.vue";
export default defineComponent({
  name:'uniappLayout',
  components:{tIndex},
  setup () {
    const store = useStore();
    const navbarRef: Ref = ref('navbarRef')
    const tabbarRef: Ref = ref('tabbarRef')
    const containerHeight_navbar = ref('0px')
    const containerHeight_tabbar = ref('0px')
    const routerComponent: Ref = ref('routerComponent')
    const metaState = computed(()=>store.getters.metaState);
    const containerStyle = reactive({
      'height': 'calc(100vh)',
      '--container-height': 'calc(100vh)'
    })
    let active = ref();
    const data = reactive({
      meta: {}
    })
    const main = reactive([
      {
        path:"home#/",
        title: '监控',
        icon: 'cashier-o',
        tabbar: '001'
      },
      {
        path:"home#alarm",
        title: '报警',
        icon: 'volume-o',
        tabbar: '002'
      },
      {
        path:"home#chart",
        title: '曲线',
        icon: 'chart-trending-o',
        tabbar: '003'
      },
      {
        path:"home#user",
        title: '我的',
        icon: 'contact',
        tabbar: '004'
      }
    ]);
    const init = function (meta) {
      const winW = document.body.offsetWidth,
      winH = document.body.offsetHeight;
      data.meta = {...data.meta,...meta}
      containerHeight_tabbar.value = '0px';
      containerHeight_navbar.value = '0px';
      nextTick(()=>{
        if(data.meta.tabbar){
          containerHeight_tabbar.value = tabbarRef.value.$el.offsetHeight + 'px';
        }
        if(data.meta.navbar){
          containerHeight_navbar.value = navbarRef.value.$el.offsetHeight + 'px';
        }
        containerStyle['--container-height'] = 'calc(100vh -' + containerHeight_tabbar.value + '-' + containerHeight_navbar.value+')';
        containerStyle['height'] = winH - parseFloat(containerHeight_tabbar.value) - parseFloat(containerHeight_navbar.value) + 'px';
        store.commit('setBaseStoreState',{
          deviceInfo: {
            width: winW,
            height: winH,
            tabbarHeight: parseFloat(containerHeight_tabbar.value),
            navbarHeight: parseFloat(containerHeight_navbar.value)
          }
        })
        active.value = main.findIndex(item=>{
          return item.tabbar === data.meta.tabbar?.id;
        })
      })
    }
    watch(()=>metaState.value,(nowData)=>{
      const meta =  store.getters.meta;
      init(meta)
    })
    onMounted(() => {
      let $route = routerComponent.value.$route;
      init($route.meta)
    })
    return {
      ...toRefs(data),
      main,
      active,
      navbarRef,
      tabbarRef,
      containerHeight_navbar,
      containerHeight_tabbar,
      routerComponent,
      containerStyle,
      handleLeft(){
        if(routerComponent.value.handleBackClick){
          routerComponent.value.handleBackClick()
        }else{
          $pathTo(-1)
        }
      },
      handleClick(item){
        routerComponent.value.handleBarClick && routerComponent.value.handleBarClick(item)
      },
      floatClick(item){
        routerComponent.value.floatClick && routerComponent.value.floatClick(item)
      }
    }
  }
})
</script>
<style lang="scss">
.app-header{
  .van-nav-bar{
    .van-nav-bar__title,
    .van-icon{
      color:var(--van-white)
    }
    background: var(--van-primary-color)
  };
  .van-nav-bar__content{
    height: 40Px;
  }
  .van-nav-bar__title{
    font-size: 14Px;
  }
}
.app-container{
  position: relative;
  height: var(--container-height);
  overflow: auto;
}
.app-container-none{
  position: relative;
  height: calc(100vh);
  overflow: auto;
}
.app-container-navbar{
  position: relative;
  height: var(--container-height);
  overflow: auto;
}
.app-container-tabbar{
  position: relative;
  height: var(--container-height);
  overflow: auto;
}
.van-tabbar-item,
.app-van-tabbar--self{
   background:var(--van-primary-color)!important;
   color:#90aee7
}
.van-tabbar-item--active{
  color:white;
  font-size: 16px;
}
</style>`)
}
module.exports = function(_path){
  var routeData = fs.readFileSync(path.resolve(_path,'../../router/index.ts'),'utf-8');
  let echoRoute = routeData.split('//uniapp')[1].replace('RouteRecordRaw','any').replace(/component([\d\w\s\_\:]+\,)/g,'');
  fs.writeFileSync(_path + '/temporaryEntry.vue', `${echoVue()}`)
  fs.writeFileSync(_path + '/temporaryEntry.ts', `${echoTs(_path,echoRoute)}`)
}